package net.asfun.jvalog.service;

import java.util.ArrayList;
import java.util.List;

import net.asfun.jvalog.common.DualCacher;
import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Message;
import net.asfun.jvalog.entity.Paper;
import net.asfun.jvalog.resource.MessageDao;
import net.asfun.jvalog.resource.MeterDao;
import net.asfun.jvalog.util.UpdateManager;
import net.asfun.jvalog.vo.Comment;
import net.asfun.jvalog.vo.Pager;
import net.asfun.jvalog.vo.Setting;


import com.google.appengine.api.datastore.KeyFactory;

public class CommentService {

	private static final String INDEX_KEY = "index";

	public static List<Comment> listRecent(int size) {
		List<Comment> comms = new ArrayList<Comment>();
		for ( Message msg : MessageDao.listPublished(size) ) {
			comms.add(new Comment(msg));
		}
		return comms;
	}

	public static List<Comment> listAll(Pager pager) {
		List<Comment> comms = new ArrayList<Comment>();
		for ( Message msg : MessageDao.listAll(pager) ) {
			comms.add(new Comment(msg));
		}
		return comms;
	}

	public static void delete(Long id) {
		Message message = JdoerFactory.jdoMessage.load(id);
		if ( message != null ) {
			if ( message.isPublished() ) {
				UpdateManager.enableCacheTask();
				MeterDao.countDown(message.getPaper(), 1);
			}
			JdoerFactory.jdoMessage.delete(message);
		}
	}

	public static void approve(Long id) {
		Message message = JdoerFactory.jdoMessage.load(id);
		message.setPublished(true);
		MeterDao.countUp(message.getPaper(), 1);
		UpdateManager.enableCacheTask();
	}

	public static void addComment(Message message, Long postId) {
		message.setPaper(KeyFactory.createKey("Paper", postId));
		if ( Setting.NEED_CHECK_COMM == 0 ) {
			message.setPublished(true);
			MeterDao.countUp(message.getPaper(), 1);
			Paper paper = JdoerFactory.jdoPaper.load(postId);
			DualCacher.remove(paper.getUri());
			DualCacher.remove(INDEX_KEY);
		}
		JdoerFactory.jdoMessage.save(message);
	}

}
